package internal

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"net/http"
	"sync"
	"yh-oss-convert/config"
)

var engine *sqlx.DB
var bucket *oss.Bucket
var initDone = false
var wg sync.WaitGroup

const urlPrefix = "https://yxpt-yuhongcs.oss-cn-beijing.aliyuncs.com/"

type DataItem struct {
	Id   int64  `db:"id"`
	Name string `db:"name"`
	Url  string `db:"url"`
}

func InitEngine(config *config.Config) error {
	connectionString := fmt.Sprintf(
		"%s:%s@%s(%s:%d)/%s?charset=utf8&parseTime=true", config.SqlConfig.User, config.SqlConfig.PassWord, "tcp",
		config.SqlConfig.Host, config.SqlConfig.Port,
		config.SqlConfig.DataBase)
	var err error
	MyLog.Debug(connectionString)

	client, err := oss.New(config.OssConfig.Endpoint, config.OssConfig.AccessKeyId, config.OssConfig.AccessKeySecret)
	if err != nil {
		MyLog.Error(err)
	}
	// 获取存储空间。
	bucket, err = client.Bucket(config.OssConfig.BucketName)
	if err != nil {
		MyLog.Error(err)
	}

	engine, err = sqlx.Connect("mysql", connectionString)
	if err != nil {
		initDone = false
		MyLog.Error(err)
	} else {
		MyLog.Info("数据库连接成功")
		initDone = true
		QueryData()
	}
	return err
}

func QueryData() {
	queryStr := "select id," + config.MyConfig.SqlConfig.ColName + " as name," + config.MyConfig.SqlConfig.
		ColUrl + " as url from " + config.MyConfig.SqlConfig.
		TableName + " where" +
		" design_file_path is not null and  design_file_path not LIKE 'https://yxpt-yuhongcs.oss-cn-beijing." +
		"aliyunc%'"

	dataItems := make([]DataItem, 0)
	MyLog.Debug(queryStr)
	err := engine.Select(&dataItems, queryStr)
	if err != nil {
		MyLog.Error(err)
	}
	ch := make(chan int, config.MyConfig.MaxGoroutine)
	for _, row := range dataItems {
		ch <- 1
		wg.Add(1)
		go downLoad(row, ch)
	}
	wg.Wait()
}

func downLoad(row DataItem, ch chan int) {
	defer wg.Done()
	client := http.Client{
		Transport:     nil,
		CheckRedirect: nil,
		Jar:           nil,
		Timeout:       0,
	}
	resp, err := client.Get(row.Url)
	if err != nil {
		MyLog.Error(err)
		<-ch
	}
	defer resp.Body.Close()
	uploadName := config.MyConfig.SqlConfig.TableName + "/" + row.Name
	err = bucket.PutObject(uploadName, resp.Body)

	if err != nil {
		MyLog.Error(err)
		<-ch
	}
	MyLog.Info(row.Name + "上传成功")
	backUrl := urlPrefix + uploadName

	updateSql := fmt.Sprintf("update %s set %s = '%s' where id = %d", config.MyConfig.SqlConfig.TableName,
		config.MyConfig.SqlConfig.ColUrl, backUrl, row.Id)
	_, err = engine.Exec(updateSql)
	if err != nil {
		MyLog.Error(err)
	}
	MyLog.Info(row.Name + "更新完毕")
	<-ch
}
